<!--
 * @Descripttion: 商机品类
 * @version:
 * @Author: lehaixia
 * @Date: 2022-10-21 10:32:52
 * @LastEditors: lehaixia
 * @LastEditTime: 2023-08-07 14:35:16
-->
<template>
  <div class="content">
    <ComHeader id="oHeader" show-statusbar fixed :border="barOpacity===1" :title="title" :white-font="false" :bg-color="headerBgColor" @get-height="handleHeadHeight" />
    <div class="detail-item">
      <div class="d-info">
        <div class="d-info-header">
          <div class="d-avatar">
            <ImageVideo lazy-load fit="cover" :src="detailInfo.avatar" />
          </div>
          <div class="d-info-name">{{ detailInfo.name }}
            <template>
              <img v-if="detailInfo.gender===1" class="icon-sex" src="@/assets/img/sex-man.png">
              <img v-else class="icon-sex" src="@/assets/img/sex-man.png">
            </template>
          </div>
          <div v-if="detailInfo.clueCustomerType" class="d-info-type">{{ getDictName('CRM_CUSTOMER_TYPE',detailInfo.clueCustomerType) }}</div>
        </div>
        <div class="d-info-code"><span>商机编码:</span><span class="d-info-value">{{ detailInfo.code }}</span></div>
        <div class="d-info-title"><span>跟进人:</span><span class="d-info-value">{{ followupUser }}</span></div>
        <div class="d-info-title"><span>电话:</span> <span class="d-info-value">{{ detailInfo.phone }}</span></div>
        <div class="d-info-title"><span>地址:</span><span class="d-info-value">{{ detailInfo.detailedAddress }}</span></div>
      </div>

      <div class="category-box" :class="{'category-box-only-add': !categoryTabsList.length && isEdit}">
        <van-tabs
          v-if="categoryTabsList.length"
          v-model="activeTab"
          class="tabs-box"
          type="card"
          inactive-color="#3C4458"
          color="#16BC83"
          :ellipsis="false"
          :class="{'tabs-box-all': !isEdit}"
          @change="handleChangeTabs"
        >
          <van-tab v-for="v in categoryTabsList" :key="v.id" :name="v.id">
            <template #title> {{ v.label }} <span class="title-more">{{ getDictName(v.type === 'FinishedProductFurniture' ?'CRM_OPTY_FP_CATEGORY_STAGE':'CRM_OPTY_CP_CATEGORY_STAGE' ,v.stage) }}</span></template>
          </van-tab>
        </van-tabs>
        <div v-if="isEdit" class="add" @click="handleOpenAddCate"><span class="add-desc">添加</span><span><van-icon name="plus" color="#16BC83" size="14" /> </span></div>
      </div>
      <!-- 用于添加品类 -->
      <div v-if="isEdit" style="display:none">
        <FieldSelect
          ref="addCategory"
          v-model="formCategory.categorySelection"
          required
          :label.sync="formCategory.categorySelectionName"
          title="品类"
          placeholder="请选择"
          :url="`/data-dict/app/v2/dictionary/CRM_CATEGORY_SELECTION`"
          label-name="dictName"
          value-name="dictCode"
          method="get"
          :params="dictParams"
          multiple
          :includes="distributorCategorySelection"
          :excludes="categoryExcludes"
          :rules="[
            { required: true, message: '请选择(必选)' }
          ]"
          @change="handleAddCategory"
        />
      </div>
      <div v-if="categoryInfo" class="d-category">
        <div class="d-category-steps">
          <!-- 步骤条 -->
          <div @click="jumpToProgress">
            <van-steps id="steps" :active="progressActive" class="d-category-step">
              <!-- 区分成品及非成品数据字典 -->
              <van-step v-for="v in dictData[categoryInfo.type === 'FinishedProductFurniture'? 'CRM_OPTY_FP_CATEGORY_STAGE':'CRM_OPTY_CP_CATEGORY_STAGE']" :key="v.id">
                <template v-slot:finish-icon> <van-icon :name="stepFinish" class="finish-class" /></template>
                <template v-slot:active-icon> <van-icon name="" class="active-class" /></template>
                <span>{{ v.dictName }}</span>
              </van-step>
            </van-steps>
          </div>
        </div>

        <div v-if="categoryInfo.type !== 'FinishedProductFurniture'">
          <!-- 方案确认 -->
          <div v-if="categoryInfo.stage !== 'MeasuringScale' && categoryInfo.stage !== 'AlreadyPlot'" class="d-confirm">
            <div class="d-title-first">
              <span class="title">方案确认</span>
              <div v-if="isShowBtn" class="button-box">
                <div v-if="categoryInfo.stage === 'ConfirmScheme'" class="d-btn" @click="handleConfirmSchemeCheck"><span>确认方案</span></div>
                <div class="d-btn" @click="handleInvite"><span>预约到店</span></div>
              </div>
            </div>
            <PopDateTimePicker
              v-if="isShowBtn"
              v-model="showInviteDate"
              title="预约到店"
              :default-value="inviteToStoreTime"
              :min-date="inviteMinDate"
              calendar-type="single"
              :show-time="true"
              @change="handleInviteSave"
            />
            <!-- 用于添加品类 -->
            <!-- <div v-if="isShowBtn" style="display:none">
              <FieldSelect
                ref="checkScheme"
                title="确认方案"
                placeholder="请选择"
                :option-data="checkReturnData"
                value-name="optyCategoryId"
                label-name="optyCategoryType"
                multiple
                @change="handleConfirmScheme"
              />
            </div> -->
            <div class="d-confirm-info">
              <div class="d-title-second">
                <span class="title">效果图</span>
                <div v-if="isShowBtn" class="d-btn" @click="handleRefresh"><span>刷新设计图</span></div>
              </div>
              <div v-for="v in designSketchList" :key="v.id" class="d-confirm-info-items" @click="jumpToImgDetail('design')">
                <div class="d-confirm-info-desc">
                  <span>{{ v.createTime }}</span>
                  <span>{{ v.belongSpace }}</span>
                  <span>{{ v.createBy }}</span>
                </div>
                <div>
                  <van-image :src="v.picUrl | filterURL" width="127px" height="82px" fit="cover" :radius="8">
                    <error-pic slot="error" />
                  </van-image>
                </div>
              </div>
            </div>

            <div class="d-confirm-info">
              <div class="d-title-second">
                <span class="title">三视图</span>
                <div v-if="isShowBtn">
                  <CFileInput accept="image/*" :multiple="false" @success="successHandle" @error="errorHandle">
                    <div class="d-btn"><span>上传三视图</span></div>
                  </CFileInput>
                </div>
              </div>
              <div v-for="v in attachmentThreeList" :key="v.id" class="d-confirm-info-items" @click="jumpToImgDetail('three')">
                <div class="d-confirm-info-desc"><span>{{ v.createTime }}</span><span>{{ v.createBy }}</span></div>
                <div>
                  <van-image :src="v.attachmentPath | filterURL" width="127px" height="82px" fit="cover" :radius="8">
                    <error-pic slot="error" />
                  </van-image>
                </div>
              </div>
            </div>
            <div v-if="isDealer" class="d-confirm-info">
              <div class="d-title-second">
                <span class="title">参考批价</span>
                <div class="flex">
                  <!-- <span v-if="ratingPriceTotal" class="title">总价: {{ ratingPriceTotal }} 元</span> -->
                  <div class="d-btn" @click="handleRefreshRating"><span>刷新批价</span></div>
                </div>
              </div>
              <div v-for="(v,i) in referRatingList.slice(0,2)" :key="i" class="d-confirm-rating">
                <div class="desc"><span>空间名称</span><span>{{ v.roomName }}</span></div>
                <div class="desc"><span>产品名称</span><span>{{ v.goodsName }}</span></div>
                <div class="desc"><span>单位</span><span>{{ v.quotationUnit }}</span></div>
                <div class="desc"><span>数量</span><span>{{ v.quantity }}</span></div>
                <div class="desc"><span>参考批价</span><span>{{ v.ratingPrice }}</span></div>
              </div>
              <div v-if="referRatingList.length > 2" class="more" @click="handleToReferRating">查看更多</div>
            </div>
          </div>
          <!-- 出图 -->
          <div v-if="categoryInfo.stage !== 'MeasuringScale'" class="d-scheme">
            <div class="d-title-first">
              <span class="title">出图信息</span>
              <div v-if="schemeData && isShowBtn" class="d-btn" @click="jumpToAddScheme('edit')"><span>更换方案</span></div>
            </div>
            <div v-if="!schemeData && isShowBtn" class="d-scheme-btn">
              <van-button type="primary" color="linear-gradient(270deg, #009E77 0%, #20CE92 100%)" :icon="ic_add" @click="jumpToAddScheme">添加方案信息</van-button>
            </div>
            <div v-if="schemeData" class="d-scheme-info">
              <div class="d-title-second"><span class="title">方案信息</span></div>
              <div class="d-scheme-desc"><span>方案名称</span><span>{{ schemeData.name }}</span> </div>
              <div class="d-scheme-desc"><span>空间</span><span>{{ schemeData.specName }}</span> </div>
              <div class="d-scheme-desc"><span>创建时间</span><span>{{ schemeData.createTimeStr }}</span></div>
              <div @click="clickPreviewHandle">
                <van-image :src="schemeData.coverPic | filterURL" width="127px" height="82px" fit="cover" :radius="8">
                  <error-pic slot="error" />
                </van-image>
              </div>
            </div>
          </div>

          <!-- 量尺 -->
          <div class="d-measure">
            <div class="d-title-first">
              <span class="title">量尺信息</span>
              <div v-if="isShowBtn" class="d-btn" @click="jumpToAddMeasure()"><span>添加量尺</span></div>
            </div>
            <div class="d-measure-info">
              <div v-for="v in measureList" :key="v.id" class="items" @click="jumpToAddMeasure(v)">
                <div class="desc"><span>{{ v.createTime }}</span><span>{{ v.createBy }}</span></div>
                <div v-if="v.addr" class="desc">定位地址:{{ v.addr }}</div>
                <div class="img-swiper-items">
                  <div v-for="vv in v.attachmentList" :key="vv.id" class="swiper-item">
                    <van-image :src="vv.attachmentPath | filterURL" width="127px" height="82px" fit="cover" :radius="8">
                      <error-pic slot="error" />
                    </van-image>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import {
  getOptyDetail,
  getOptyCategoryData,
  getMeasureInfo,
  queryBindScheme,
  getDesignSketch,
  getAttachment,
  addOptyCategory,
  confirmSchemeCheck,
  confirmScheme,
  refreshDesignSketch,
  uploadFile,
  inviteToStore,
  queryDesignerByOptyId,
  queryGuidByClueCustomerId,
  getDistributorCategorySelection,
  getRatingPrice
} from '@/apis/optyCategory'
import { getDictByPatchType } from '@/apis/dataDict'
import { json2FormData } from '@/utils'
import ic_add from '@/assets/category/ic_add@2x.png'
import stepFinish from '@/assets/category/step-finish.png'
import FieldSelect from '@/components/FieldSelect'
import CFileInput from '@/components/CFileInput'
import PopDateTimePicker from '@/components/PopDateTimePicker'
import { parseTime } from '@/utils'
import errorAvatarIcon from '@/assets/defaultAvatar.png'
import ErrorPic from '@/components/ErrorPic'
import { ImagePreview } from 'vant'
import { bus } from '@/utils/bus'
import ImageVideo from '@/components/ImageVideo'

export default {
  name: 'EditOptyCategory',
  components: { FieldSelect, CFileInput, PopDateTimePicker, ErrorPic, ImageVideo },
  props: {},
  data() {
    const date = new Date()
    return {
      errorAvatarIcon, // 头像加载失败显示
      ic_add,
      stepFinish,
      isEdit: false, // 当前页面是编辑页还是详情页
      detailInfo: '', // 商机详情
      followupUser: '', // 跟进人信息
      activeTab: '', // 品类tabs切换
      categoryInfo: '', // 品类信息

      categoryTabsList: [], // 品类列表 已添加
      categoryList: [], // 品类列表 数据字典
      categoryMap: {}, // 品类映射关系
      dictData: '', // 数据字典集合
      progressActive: '', // 进度条进度节点
      measureList: [], // 量尺信息
      schemeData: '', // 方案信息
      designSketchList: [], // 效果图信息
      attachmentThreeList: [], // 三视图列表信息
      formCategory: { // 品类添加
        categorySelection: [],
        categorySelectionName: ''
      },
      submiting: false,
      dictParams: { query: { appCode: 'top2-crm', domainCode: 'marketing' }, type: 0 },
      categoryExcludes: [],
      distributorCategorySelection: [], // 经销商下的品类
      checkReturnData: [], // 确认方案返回
      inviteToStoreTime: parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}'), // 预约时间
      inviteMinDate: date,
      showInviteDate: false,
      statusBarHeight: 0, // 状态栏高度
      barOpacity: 0, // 导航栏透明度
      headHeight: 50, // header高度
      isDealer: false, // 是否经销商 用于判断是否显示参考批价
      referRatingList: [], // 参考批价列表
      ratingPriceTotal: 0
    }
  },
  // 监听属性 类似于data概念
  computed: {
    // 是不是显示品类下的操作按钮
    isShowBtn() {
      const whiteList = ['MeasuringScale', 'AlreadyPlot', 'ConfirmScheme', 'PlaceOrder']
      return this.isEdit && this.categoryInfo && this.categoryInfo.isStop === 0 && whiteList.includes(this.categoryInfo.stage)
    },
    headerBgColor() {
      return `rgba(250, 251, 254, ${this.barOpacity > 1 ? 1 : this.barOpacity})`
    },
    title() {
      return this.isEdit ? '编辑' : '商机信息'
    }
  },
  // 监控data中的数据变化
  watch: {

  },
  async created() {
    bus.$on('refreshCustomerItem', this.refreshCustomerItem)

    const { id } = this.$route.query
    const { userInfo = '', statusBarHeight } = this.$store.getters
    this.statusBarHeight = statusBarHeight

    const positionCodes = userInfo && userInfo.positionCodes || [] // 当前租户下的全部职位
    const whiteBlank = ['top_designer', 'top_design_mg'] // 判断是否包含设计师/设计师主管，有设计师/设计师主管则允许编辑
    this.isEdit = !!positionCodes.filter(v => whiteBlank.includes(v)).length
    this.isDealer = !!positionCodes.find(v => v === 'top_0' || v === 'top_dis')

    this.initOptyDetail(id)
    const dictTypeCodes = ['CRM_CATEGORY_SELECTION', 'CRM_OPTY_CP_CATEGORY_STAGE', 'CRM_OPTY_FP_CATEGORY_STAGE', 'CRM_CUSTOMER_TYPE']

    const dictData = await getDictByPatchType({ dictTypeCodes })
    this.dictData = dictData
    this.categoryList = dictData && dictData.CRM_CATEGORY_SELECTION || []
    this.arrayToObject()
    await this.initOptyCategory(id)
    // 查询经销商下的品类
    if (this.detailInfo.disCode) this.distributorCategorySelection = await getDistributorCategorySelection({ disCode: this.detailInfo.disCode })
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll, { passive: true })
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll, { passive: true })
  },
  beforeRouteLeave(to, from, next) {
    if (to.path === '/customer/detail') {
      this.$removeKeepAliveCache(this)
    }
    next()
  },
  // 方法集合
  methods: {
    // 将品类列表转成对象
    arrayToObject() {
      const map = {}
      this.categoryList.forEach(item => {
        const key = item.dictCode
        map[key] = item.dictName
      })
      this.categoryMap = map
    },
    // 商机详情
    async initOptyDetail(id, getmore = true) {
      const res = await getOptyDetail(id)
      if (res.success === 1 && res.data) {
        this.detailInfo = res.data
        if (getmore) this.getFollowupUser()
      }
    },
    // 获取跟进人信息
    async getFollowupUser() {
      const { id, clueCustomerId } = this.detailInfo
      const designerList = await queryDesignerByOptyId({ optyId: id }) || []
      const guideList = await queryGuidByClueCustomerId({ clueCustomerId }) || []

      const arrList = designerList.concat(guideList)
      // 去重且返回名称
      const hash = {}
      const newArray = arrList.reduce((item, next) => {
        hash[next.employeeId] ? '' : hash[next.employeeId] = true && item.push(next.userTrueName)
        return item
      }, [])
      this.followupUser = newArray.join(',')
    },
    // 已添加品类信息
    async initOptyCategory(id) {
      const otherFilters = [{ id: 'optyId', property: 'optyId', value: id, operator: '=' }]
      const sortersRaw = [{ 'id': 'isStop', 'property': 'isStop', 'direction': 'asc' }, { 'id': 'createTime', 'property': 'createTime', 'direction': 'asc' }]

      const data = json2FormData({
        pageFlag: false,
        filtersRaw: JSON.stringify(otherFilters),
        sortersRaw: JSON.stringify(sortersRaw)
      })

      const records = await getOptyCategoryData(data) || []
      records.forEach((v, i) => {
        const label = this.categoryMap[v.type] || ''
        v.label = label + (v.isStop === 1 ? '终止' : '')
      })
      this.categoryTabsList = records
      // 赋默认值
      if (records.length > 0 && !this.activeTab) {
        this.activeTab = records[0].id
        this.handleChangeTabs()
      }
      this.categoryExcludes = records.filter(v => v.isStop === 0).map(v => v.type) // 用于添加方案过滤数据

      // 刷新品类列表时使用 找到上一次点击的按钮
      if (this.activeTab) {
        const find = this.categoryTabsList.find(v => v.id === this.activeTab)

        // 当品类状态更改时 品类信息及进度条相关信息更新
        if (find !== -1 && find.stage !== this.categoryInfo.stage) {
          this.categoryInfo = find !== -1 ? find : ''// 各品类信息
          this.updateProgressActive() // 进度条信息
        }
      }
    },
    // 获取量尺信息
    initMeasure() {
      const otherFilters = [{ id: 'optyId', property: 'optyId', value: this.detailInfo.id, operator: '=' },
        { id: 'optyCategoryId', property: 'optyCategoryId', operator: '=', value: this.categoryInfo.id }
      ]
      const data = json2FormData({
        pageFlag: false,
        filtersRaw: JSON.stringify(otherFilters),
        sort: 'createTime',
        order: 'desc'
      })
      getMeasureInfo(data).then(res => {
        const { success, data } = res
        if (success === 1 && data && data.records) {
          this.measureList = data.records || []
        }
      })
    },
    // 获取绑定的方案
    initScheme() {
      const params = { optyCategoryId: this.categoryInfo.id }
      queryBindScheme(params).then(res => {
        const { success, data } = res
        if (success === 1) {
          this.schemeData = data || ''
        }
      })
    },
    // 获取效果图
    initDesignSketch() {
      const otherFilters = [{ id: 'optyId', property: 'optyId', value: this.detailInfo.id, operator: '=' },
        { id: 'optyCategoryId', property: 'optyCategoryId', operator: '=', value: this.categoryInfo.id }
      ]
      const data = json2FormData({
        filtersRaw: JSON.stringify(otherFilters),
        sort: 'createTime',
        order: 'desc',
        page: 1,
        rows: 1
      })
      getDesignSketch(data).then(res => {
        const { success, data } = res
        if (success === 1 && data && data.records) {
          this.designSketchList = data.records || []
        }
      })
    },
    // 获取三视图
    initAttachment() {
      const otherFilters = [{ id: 'moduleType1', property: 'moduleType', operator: '=', value: 'ThreeViews' },
        { id: 'objectId', property: 'objectId', operator: '=', value: this.categoryInfo.id }
      ]
      const data = json2FormData({
        filtersRaw: JSON.stringify(otherFilters),
        sort: 'createTime',
        order: 'desc',
        page: 1,
        rows: 1
      })
      getAttachment(data).then(res => {
        const { success, data } = res
        if (success === 1 && data && data.records) {
          this.attachmentThreeList = data.records || []
        }
      })
    },
    // 更新进度条节点信息
    updateProgressActive() {
      const { type, stage } = this.categoryInfo
      const { CRM_OPTY_FP_CATEGORY_STAGE, CRM_OPTY_CP_CATEGORY_STAGE } = this.dictData
      const list = type === 'FinishedProductFurniture' ? CRM_OPTY_FP_CATEGORY_STAGE : CRM_OPTY_CP_CATEGORY_STAGE
      this.progressActive = list.findIndex(v => v.dictCode === stage)

      // 已到达的进度在中间
      this.$nextTick(() => {
        var element = document.querySelector('.van-step--process')
        // element && element.scrollIntoView({
        //   behavior: 'smooth',
        //   inline: 'center'
        // })
        element && element.scrollIntoViewIfNeeded()
      })
    },
    // 切换品类
    handleChangeTabs(name, title) {
      // console.log(this.activeTab, name, title)
      // 切换品类时 清空原列表详情中的值
      this.progressActive = ''
      this.measureList = []
      this.schemeData = ''
      this.designSketchList = []
      this.attachmentThreeList = []

      const find = this.categoryTabsList.find(v => v.id === this.activeTab)
      this.categoryInfo = find !== -1 ? find : ''// 各品类信息
      // 进度条信息
      this.updateProgressActive()

      const { type, stage } = this.categoryInfo
      if (type !== 'FinishedProductFurniture') {
        if (stage !== 'MeasuringScale' && stage !== 'AlreadyPlot') {
          this.initDesignSketch() // 获取效果图信息
          this.initAttachment() // 获取三视图信息
        }
        if (stage !== 'MeasuringScale') this.initScheme() // 获取绑定的方案
        this.initMeasure() // 量尺信息
      }
    },
    // 打开品类添加弹框
    handleOpenAddCate() {
      this.$refs.addCategory && this.$refs.addCategory.handleClickOpen()
    },
    // 添加品类
    handleAddCategory(val) {
      if (this.submiting) return
      const categorySelection = val.map(v => v.dictCode).join(',')
      const { clueCustomerId, id } = this.detailInfo
      const data = { categorySelection, clueCustomerId, optyId: id, schemeId: null }
      this.submiting = true
      addOptyCategory(data).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$toast(res.msg || '添加成功')
          // 清空选项
          this.formCategory = {
            categorySelection: [],
            categorySelectionName: ''
          }
          // 添加品类后刷新品类列表
          this.$nextTick(() => {
            this.initOptyCategory(this.detailInfo.id)
          })
        }
      }).catch((e) => {
        this.submiting = false
      })
    },
    // 获取数据字典值对应的名称
    getDictName(dictType, dictCode) {
      let name = ''
      if (this.dictData && this.dictData[dictType]) {
        const index = this.dictData[dictType].findIndex(v => v.dictCode === dictCode)
        if (index > -1) {
          name = this.dictData[dictType][index].dictName
        }
      }
      return name
    },
    handleHeadHeight(h) {
      // console.log('当前head高度为', h)
      this.headHeight = h
    },
    // 调整至商机详情页
    jumpToProgress() {
      const { id, stage, type } = this.categoryInfo
      const dictTypeCode = type === 'FinishedProductFurniture' ? 'CRM_OPTY_FP_CATEGORY_STAGE' : 'CRM_OPTY_CP_CATEGORY_STAGE'
      this.$router.push({
        path: '/customer/category/detail/progress',
        query: { id: id, stage: stage, dictTypeCode }
      })
    },
    // 跳转到量尺编辑页
    jumpToAddMeasure(data) {
      // 该页面是否能编辑且没有终止 能编辑的话 跳转到编辑页 '/customer/category/add/measure 否则跳转至详情页 /customer/category/detail/imginfo
      if (this.isShowBtn) {
        this.$router.push({
          path: '/customer/category/add/measure',
          query: {
            customerSource: this.detailInfo.disCustomerFirstSource, //  Online 线上， Offline 线下
            optyId: this.detailInfo.id, // 商机id
            optyCategoryId: this.categoryInfo.id, // 品类id
            id: data && data.id // 量尺id
          }
        })
      } else {
        this.jumpToImgDetail('measure')
      }
    },
    // 跳转到添加/更改方案页
    jumpToAddScheme() {
      this.$router.push({
        path: '/customer/category/add/scheme',
        query: {
          customerSource: this.detailInfo.disCustomerFirstSource, //  Online 线上， Offline 线下
          id: this.categoryInfo.id, // 品类id
          type: this.categoryInfo.type, // 品类类型
          isHaveScheme: this.schemeData ? 1 : 0 // 是否已添加方案 0:无 1:有
        }
      })
    },
    // 跳转至查看各阶段详情信息
    jumpToImgDetail(page) {
      this.$router.push({
        path: '/customer/category/detail/imginfo',
        query: {
          optyId: this.detailInfo.id, // 商机id
          optyCategoryId: this.categoryInfo.id, // 品类id
          page: page // 效果图 design 三视图 three
        }
      })
    },
    // 方案查看图片
    clickPreviewHandle() {
      ImagePreview({
        images: [this.schemeData.coverPic],
        startPosition: 0
      })
    },
    // 确认方案
    handleConfirmSchemeCheck() {
      if (this.submiting) return
      const { id: optyCategoryId, optyId } = this.categoryInfo
      const data = { optyCategoryId, optyId }

      // 确认方案前的检查
      this.$dialog.confirm({
        message: '是否继续确认方案'
      }).then(() => {
        this.submiting = true
        confirmSchemeCheck(data).then(res => {
          this.submiting = false
          // 确认方案
          if (res.success === 1 && res.data) {
            this.checkReturnData = res.data
            // this.$refs.checkScheme.handleClickOpen()
            const { id, setmealSaleAmount } = this.detailInfo
            this.$router.push({
              name: 'ConfirmScheme',
              params: { data: res.data, optyId: id, setmealSaleAmount }
            })
          }
        }).catch(e => {
          console.error(e)
          this.submiting = false
        })
      })
    },
    // 选择需要确认方案的品类
    handleConfirmScheme(val) {
      if (this.submiting) return

      this.submiting = true
      confirmScheme(val).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$toast(res.msg || '确认方案成功')
          // 刷新品类列表
          this.$nextTick(() => {
            this.initOptyCategory(this.detailInfo.id)
          })
        }
      }).catch(() => {
        this.submiting = false
      })
    },
    // 打开时间选择界面
    handleInvite() {
      this.showInviteDate = true
    },
    // 预约时间保存
    handleInviteSave(val) {
      if (this.submiting) return
      const data = {
        optyCategoryId: this.categoryInfo.id,
        inviteToStoreTime: val
      }
      this.submiting = true
      inviteToStore(data).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$toast(res.msg || '预约到店成功!')
        }
      }).catch(() => {
        this.submiting = false
      })
    },
    // 刷新效果图
    handleRefresh() {
      if (this.submiting) return
      const { id = '' } = this.detailInfo
      const { designId = '' } = this.schemeData

      const data = {
        optyId: id,
        designId: designId
      }

      this.$dialog.confirm({
        title: '是否刷新效果图',
        message: '确认刷新效果图'
      }).then(() => {
        refreshDesignSketch(data).then(res => {
          if (res.success === 1) {
            this.initDesignSketch()
            this.$toast(res.msg || '刷新成功!')
          }
        })
      })
    },
    // 三视图上传成功后触发
    successHandle(e) {
      this.changeHandle(e)
    },
    async changeHandle(e) {
      let files = e.target.files
      files = [].slice.call(files)

      const all = []
      for (const file of files) {
        var isImg = file.type.indexOf('image/') > -1
        if (!isImg) {
          const msg = `只能上传图片文件！`
          this.$toast.fail(msg)
          all.push(Promise.reject(msg))
          continue
        }
        // 验证文件大小
        const size = (file.size || 0)
        if (this.maxSize < size) {
          const msg = `上传图片大小不能超过${this.maxSize / 1024 / 1024}M!`
          this.$toast.fail(msg)
          all.push(Promise.reject(msg))
          continue
        }
        all.push(file)
      }
      const toast = this.$toast.loading({
        forbidClick: true,
        message: '图片上传中...',
        duration: 0
      })

      const allPost = []
      await Promise.all(all).then(files => {
        files.forEach(file => {
          const p = new Promise((resolve, reject) => {
            const forms = new FormData()
            forms.append('file', file)
            forms.append('moduleType', 'ThreeViews')
            forms.append('objectId', this.categoryInfo.id)

            uploadFile(forms).then(res => {
              const { success, data } = res
              if (success === 1 && data) {
                this.initAttachment()
              }
              resolve(data)
            }).catch(e => {
              reject(e)
            })
          })
          allPost.push(p)
        })
      })
      Promise.all(allPost).then(res => {
        toast.clear()
      }).catch(e => {
        toast.clear()
        this.$toast.fail('网路请求超时')
        console.error(e)
      })
    },
    // 三视图上传失败后触发
    errorHandle(err) {
      this.$toast.fail(err.toString())
    },
    // 滑动时改变颜色透明度
    handleScroll() {
      const topEl = document.querySelector(`#oHeader`)
      if (topEl) {
        const top = topEl.getBoundingClientRect().top
        if (top >= 0) {
          this.barOpacity = 0
          return
        }
        let barOpacity = 1 - (top + this.statusBarHeight) / this.statusBarHeight
        if (barOpacity > 1) barOpacity = 1
        this.barOpacity = barOpacity
      }
    },
    refreshCustomerItem({ type, isRefreshCategory }) {
      if (type === 'addMeasure') {
        this.$nextTick(() => {
          if (isRefreshCategory) this.initOptyCategory(this.detailInfo.id) // 刷新品类列表
          this.initMeasure() // 刷新量尺
        })
        return
      }
      if (type === 'editMeasure') {
        this.$nextTick(() => {
          this.initMeasure() // 刷新量尺
        })

        return
      }
      if (type === 'scheme') {
        this.$nextTick(() => {
          if (isRefreshCategory) this.initOptyCategory(this.detailInfo.id) // 刷新品类列表
          this.initScheme() // 刷新方案
        })
        return
      }
      if (type === 'confirmScheme') {
        this.$nextTick(() => {
          this.initOptyCategory(this.detailInfo.id) // 刷新品类列表
          this.initOptyDetail(this.detailInfo.id, false) // 刷新商机详情
        })
        return
      }
    },
    // 刷新批价
    handleRefreshRating() {
      getRatingPrice({ optyCategoryId: this.categoryInfo.id }).then(res => {
        if (res.success === 1 && res.data) {
          const { schemeGoodsDTOS = [], total = 0 } = res.data
          this.referRatingList = schemeGoodsDTOS
          this.ratingPriceTotal = total
        }
      })
    },
    // 跳转到参考批价详情页
    handleToReferRating() {
      this.$router.push({
        name: 'ReferRating',
        query: { optyCategoryId: this.categoryInfo.id },
        params: { total: this.ratingPriceTotal, list: this.referRatingList }
      })
    }
  }
}
</script>
<style lang='less' scoped>
/* @import url(); 引入css类 */
  .content {
    background-image: url('~@/assets/category/edit_bg@2x.png');
    background-repeat: no-repeat;
    background-size: 100% auto;
    .detail-item {
      padding: 16px 0;
    }
  }
  .d-info {
    background: #FFFFFF;
    box-shadow: 0px 3px 30px 0px rgba(209,211,218,0.56);
    border-radius: 14px;
    margin: 16px 20px;
    padding: 16px;
    .d-info-header {
      position: relative;
      padding-left: 78px;
      padding-bottom: 5px;
      min-height: 30px;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      justify-content: space-between;
       .d-avatar {
        position: absolute;
        left: 0;
        bottom: 0;
        z-index: 1;
        width: 68px;
        height: 68px;
        box-sizing: border-box;
        background: #FFFFFF;
        box-shadow: 0px 0px 30px 0px rgba(0,0,0,0.06);
        border-radius: 14px;
        border: 2px solid #FFFFFF;
        border-radius: 16px;
        overflow: hidden;
        /deep/.image-video{
          border-radius: 14px;
        }
      }
      .d-info-name {
        line-height: 25px;
        font-size: 18px;
        font-weight: 600;
        color: #343640;
        .icon-sex{
          width: 12px;
          height: 12px;
          margin-left: 6px;
        }
      }
      .d-info-type {
        min-width: 40px;
        height: 20px;
        background-color: rgba(238, 103, 26, 0.1);
        border-radius: 6px;
        font-size: 10px;
        font-weight: 500;
        color: #EE671A;
        line-height: 20px;
        padding: 0 10px 0 11px;
      }
    }

    .d-info-code {
      // padding-top: 16px;
      padding-bottom: 14px;
      span {
        font-size: 14px;
        font-weight: 500;
        color: #3C4458;
        line-height: 20px;
      }
    }
    .d-info-title {
      padding: 2px 0;

      span {
        width: 211px;
        font-size: 12px;
        font-weight: 400;
        color: #979AA9;
        line-height: 17px;
        word-break: break-all;
      }
      .d-info-value {
        padding-left: 6px;
      }
    }
  }

  .category-box-only-add {
    justify-content: end !important;
  }
  .category-box {
    // position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .tabs-box-all {
      width: 100% !important;
    }
    .tabs-box {
      width: calc(100vw - 75px);
      // position: relative;
      /deep/ .van-tabs__wrap, /deep/ .van-tabs__nav--card {
        height: 40px;
      }
      /deep/ .van-tabs__nav--card {
        border: none;
        border-radius: 8px 8px 0px 0px;
        margin: 0;
        background-color:transparent;
      }

      /deep/  .van-tab {
        border: 1px solid #DFF4F0 !important;
        border-radius: 8px 8px 0px 0px;
        background-color: #fff;
        font-size: 16px;
        font-weight: 600;
        line-height: 22px;
      }
      /deep/ .van-tabs__nav--card .van-tab.van-tab--active {
        background-color: #DFF4F0 !important;
        color: #16BC83 !important;

        .title-more {
          background-color: rgba(255,255,255,0.67);
        }
      }
      .title-more {
        border-radius: 6px;
        border: 1px solid rgba(22,188,131,0.2);
        padding: 3px 10px;
        font-size: 10px;
        font-weight: 500;
        line-height: 14px;
      }
    }
    .add {
      // position: absolute;
      // right: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 70px;
      // height: 40px;
      background: #FFFFFF;
      border-radius: 8px 8px 0px 0px;
      border: 1px solid #DFF4F0;
      padding: 9px;

      span {
        font-size: 16px;
        font-weight: 600;
        color: #16BC83;
        line-height: 22px;
      }

      .add-desc {
        min-width: 32px;
        padding-right: 6px;
      }
    }
  }

  .d-category {
    background: #fff;

    .d-category-steps {
      padding: 25px 16px 19px;
      .d-category-step {
        padding: 0;
        overflow-x: auto;
        &::-webkit-scrollbar {
          display: none;
        }
        /deep/ .van-steps__items {
          height: 60px;
          padding-bottom: 0;
          margin: 0;
        }

        /deep/ .van-step {
          // min-width: 70px;
          flex: 0 0 70px;
          .van-step__title {
            position: absolute;
            bottom: -10px;
            font-size: 12px;
            font-weight: 600;
            color: #3C4458;
            line-height: 17px;
            transform: translateY(-50%);
            margin-left: 0;
            word-break: keep-all;
            // transform: translate(50%, 50%);
          }
        }

        /deep/ .van-step__circle {
          width: 10px;
          height: 10px;
          background: #BBEAEA;
          box-shadow: 0px 2px 6px 0px rgba(10,159,156,0.19);
          border-radius: 9px;
        }
        /deep/ .van-step--horizontal {
          float: none;
        }
        /deep/ .van-step--horizontal .van-step__circle-container {
          padding: 0;
          left: auto;
        }
        /deep/ .van-step--horizontal:last-child {
          position: unset;

          .van-step__circle-container {
            right: auto;
          }
        }

        /deep/ .van-step--horizontal .van-step__line {
          height: 2px;
          background: #16BC83;
          border-radius: 2px;
          opacity: 0.2;
          top: 29px;
        }

        /deep/ .van-step--finish {
          .van-step__line {
            opacity: 1;
          }
          .finish-class {
            width: 32px;
            height: 18px;
            background: #16BC83;
            box-shadow: 0px 2px 6px 0px rgba(10,159,156,0.19);
            border-radius: 9px;

            img {
              width: 100%;
              height: 100%;
            }
          }
        }
        /deep/ .van-step--process {
          .active-class {
            width: 11px;
            height: 11px;
            background: #16BC83;
            box-shadow: 0px 2px 6px 0px rgba(10,159,156,0.19);
            border-radius: 9px;
          }
        }
      }
    }
    // 一级title
    .d-title-first {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 16px;

      .title {
        font-size: 16px;
        font-weight: 600;
        color: #3C4458;
        line-height: 22px;
      }

      .button-box {
        display: flex;
        align-items: center;
      }

      .d-btn {
        background: rgba(22,188,131,0.12);
        border-radius: 8px;
        padding: 0 16px;
        margin-left: 12px;
        span {
          height: 32px;
          font-size: 12px;
          font-weight: 600;
          color: #16BC83;
          line-height: 32px;
        }
      }
    }
    // 二级title
    .d-title-second {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 54px;
      margin-bottom: 16px;

      &::after{
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        height: 1px;
        background: #D9DDE2;
      }
      .title {
        font-size: 14px;
        font-weight: 500;
        color: #16BC83;
        line-height: 20px;
      }

      .flex {
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
      .d-btn {
        border-radius: 8px;
        border: 1px solid rgba(22,188,131,0.44);
        margin-left: 12px;
        padding: 0 10px;
        span {
          height: 32px;
          font-size: 12px;
          font-weight: 600;
          color: #16BC83;
          line-height: 32px;
        }
      }
    }

    .d-measure {
      padding: 16px 16px 19px;
      .d-measure-info {
        .items {
          padding: 8px 0 16px 16px;
          background: #F8F8FA;
          border-radius: 8px;
          margin-bottom: 16px;

          .desc {
            padding-bottom: 14px;
            font-size: 12px;
            font-weight: 400;
            color: #3C4458;
            line-height: 17px;
            span {
              padding-right: 34px;
            }
          }

        .img-swiper-items {
          display: flex;
          overflow-x: auto;
          .swiper-item {
            padding-right: 16px;
          }
          &::-webkit-scrollbar {
            display: none;
          }
        }
      }
    }
  }

    .d-scheme {
      padding: 16px 16px 19px;
      .d-scheme-btn {
        text-align: center;
        padding-top: 10px;
        /deep/ .van-button--normal {
          padding: 0 67px 0 68px;
          border-radius: 12px;
        }
        /deep/ .van-button {
          height: 48px;
        }
        /deep/ .van-button__icon {
          font-size: 16px;
          height: 16px;
        }
      }

      .d-scheme-info {
        background: #F8F8FA;
        border-radius: 8px;
        padding: 0 16px 16px;

        .d-scheme-desc {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding-bottom: 12px;
          font-size: 12px;
          line-height: 17px;
          span {
            &:nth-of-type(1) {
              font-weight: 500;
              color: #111111;
            }
            &:nth-of-type(2) {
              font-weight: 400;
              color: #7D8091;
            }
          }
        }
      }
    }
    .d-confirm {
      padding: 16px;

      .d-confirm-info {
        background: #F8F8FA;
        border-radius: 8px;
        margin-bottom: 16px;
        padding: 0 16px 16px;
        &:nth-last-of-type(1) {
          margin-bottom: 0;
        }

        .d-confirm-info-items {
          .d-confirm-info-desc {
            padding-bottom: 12px;
            span {
              font-size: 12px;
              font-weight: 400;
              color: #3C4458;
              line-height: 17px;
              padding-right: 20px;
            }
          }
        }

        .d-confirm-rating {
          position: relative;
          padding-bottom: 8px;
          .desc {
            display: flex;
            align-items: center;
            justify-content: space-between;

            font-size: 12px;
            font-weight: 400;
            color: #3C4458;
            line-height: 17px;
            padding-bottom: 8px;

            span:first-of-type {
              color: #000;
              white-space: nowrap;
            }
            span:last-of-type {
              white-space: normal;
              margin-left: 20px;
            }
          }

          // &:first-of-type {
            &::after {
              content: '';
              position: absolute;
              left: 0;
              right: 0;
              bottom: 8px;
              height: 1px;
              background: #D9DDE2;
            }
          // }

          &:nth-last-of-type(2) {
            &::after {
              display: none;
            }
          }
        }
      }
      .more {
        text-align: center;
        padding-top: 8px;
        font-size: 12px;
        font-weight: 600;
        color: #16BC83;
        cursor: pointer;
      }
    }
  }
</style>
